package com.zdlee.netty.server19.server.handler;

import com.zdlee.netty.server19.protocol.request.QuitGroupRequestPacket;
import com.zdlee.netty.server19.protocol.response.QuitGroupResponsePacket;
import com.zdlee.netty.server19.util.SessionUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;

/**
 * @author zdlee
 * @description: ${DESCRIPTION}
 * @create 2018-12-01 16:08
 */
@ChannelHandler.Sharable
public class QuitGroupRequestHandler extends SimpleChannelInboundHandler<QuitGroupRequestPacket> {

    public static final QuitGroupRequestHandler INSTANCE = new QuitGroupRequestHandler();

    private QuitGroupRequestHandler() {

    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, QuitGroupRequestPacket msg) throws Exception {
        //1.获取群对应的channelGroup,然后将当前用户的channel移除
        String groupId=msg.getGroupId();
        ChannelGroup channelGroup= SessionUtil.getChannelGroup(groupId);
        channelGroup.remove(ctx.channel());
        //2.构造退群响应发送给客户端
        QuitGroupResponsePacket responsePacket=new QuitGroupResponsePacket();

        responsePacket.setGroupId(msg.getGroupId());
        responsePacket.setSuccess(true);
        ctx.channel().writeAndFlush(responsePacket);


    }
}
